package com.zx.base.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.zx.base.ctrl.Constant;
import com.zx.base.widget.ShowDialog;
import com.zx.tv.R;
import com.zx.tv.ui.WeatherActivity;



public class UpdateVersion {

	private Context mContext;
	
	private ShowDialog dialog ;
	
	//提示语
	private String updateMsg = "检测到可更新的版本，是否更新？";
	
	//返回的安装包url
	private String apkUrl = "";
	
	
	
	private Dialog downloadDialog;
	 /* 下载包安装路径 */
    private static final String savePath = "/sdcard/mengyou/";
    private String savePath_down = "download/";
    
    private String saveFileName = savePath + savePath_down + "newtv.apk";

    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;

    
    private static final int DOWN_UPDATE = 1;
    
    private static final int DOWN_OVER = 2;
    
    private int progress;
    
    private Thread downLoadThread;
    
    private boolean interceptFlag = false;
    
    private String content = "";
    
    private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				
				
				installApk();
				break;
			case 3:
				
				Toast toast1 = Toast.makeText(mContext, "更新失败",
						Toast.LENGTH_SHORT);
				toast1.setGravity(Gravity.CENTER, 0, 0);
				toast1.show();
				
				downloadDialog.dismiss();
				
				break;
			default:
				break;
			}
    	};
    };
    
	public UpdateVersion(Context context, String url, String content) {
		this.mContext = context;
		this.apkUrl = url;
		this.content = content;
	}
	
	//外部接口让主Activity调用
	public void checkUpdateInfo(){
		//showNoticeDialog();
		boolean bl = false;
		dialog = new ShowDialog((WeatherActivity)mContext, "版本升级", content, "立即升级", "以后再说", bl);
		dialog.show();
		dialog.bt_yes.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				dialog.dlg.dismiss();
				showDownloadDialog();
			}
		});
		
		dialog.bt_no.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				dialog.dlg.dismiss();
				
			}
		});
		
	}
	
	public Dialog buildDialog1(Context context) { 
		boolean bl = false;
		
        AlertDialog.Builder builder = new AlertDialog.Builder(context);   
        builder.setTitle(updateMsg);   
        builder.setPositiveButton("立即升级",   
                new DialogInterface.OnClickListener() {   
                    public void onClick(DialogInterface dialog, int whichButton) {   
                    	dialog.dismiss();
                    	showDownloadDialog();
                    }   
                });   
        builder.setNegativeButton("以后再说",   
                new DialogInterface.OnClickListener() {   
                    public void onClick(DialogInterface dialog, int whichButton) {   

                    	dialog.dismiss();
                    }   
                });   
        return builder.create();   
  
    }
	
	
	
	private void showDownloadDialog(){
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("正在更新");
		
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar)v.findViewById(R.id.progress);
		
		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
				((WeatherActivity)mContext).finish();
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();
		
		downloadApk();
	}
	
	private Runnable mdownApkRunnable = new Runnable() {	
		@Override
		public void run() {
			try {
				if(Constant.debug)Log.d("TMG", "update apk url = " + apkUrl);
				URL url = new URL(apkUrl);
			
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.setConnectTimeout(3000);
				conn.setReadTimeout(30000);
				conn.setRequestMethod("GET");
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if(!file.exists()){
					file.mkdir();
				}
				
				File file1 = new File(savePath + savePath_down);
				if(!file1.exists()){
					file1.mkdir();
				}
				
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);
				
				int count = 0;
				byte buf[] = new byte[1024];
				
				do{   		   		
		    		int numread = is.read(buf);
		    		count += numread;
		    	    progress =(int)(((float)count / length) * 100);
		    	    //更新进度
		    	    mHandler.sendEmptyMessage(DOWN_UPDATE);
		    		if(numread <= 0){	
		    			//下载完成通知安装
		    			downloadDialog.dismiss();
		    			mHandler.sendEmptyMessage(DOWN_OVER);
		    			break;
		    		}
		    		fos.write(buf,0,numread);
		    	}while(!interceptFlag);//点击取消就停止下载.
				
				fos.close();
				is.close();
			} catch (Exception e) {
				
				mHandler.sendEmptyMessage(3);
				Log.e("TMG", "update time out");
				e.printStackTrace();
			}
			
		}
	};
	
	 /**
     * 下载apk
     * @param url
     */
	
	private void downloadApk(){
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}
	 /**
     * 安装apk
     * @param url
     */
	private void installApk(){
		File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }    
        
	
        Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		String type = getMIMEType(apkfile);
		intent.setDataAndType(Uri.fromFile(apkfile), type);
		mContext.startActivity(intent);

		
	}
	
	private String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else if (end.equals("apk")) {
			type = "application/vnd.android.package-archive";
		} else {
			type = "*";
		}
		if (end.equals("apk")) {

		} else {
			type = "/*";
		}
		return type;
	}

}
